// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
const _ = db.command
var $ = db.command.aggregate
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let data = {}
  await db.collection('eve').aggregate()
    .lookup({
      from: 'user',
      localField: '_openid',
      foreignField: '_openid',
      as: 'host',
    })
    .match({
      _id: _.in(event.joinedId),
      bool_end: event.end,
      type: event.type
    })
    .sort({
      start_time: 1
    })
    .replaceRoot({
      newRoot: $.mergeObjects([ $.arrayElemAt(['$host', 0]), '$$ROOT' ])
    })
    .project({
      host: 0
    })
    .end()
    .then(res => {
      data = res.list
    })
    .catch(res => console.log(res))

  return data
}